{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# nqueens_sat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/examples/nqueens_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/python/nqueens_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "CP/SAT model for the N-queens problem.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "from ortools.sat.colab import flags\n",
    "from ortools.sat.python import cp_model\n",
    "\n",
    "_SIZE = flags.define_integer(\"size\", 8, \"Number of queens.\")\n",
    "\n",
    "\n",
    "class NQueenSolutionPrinter(cp_model.CpSolverSolutionCallback):\n",
    "    \"\"\"Print intermediate solutions.\"\"\"\n",
    "\n",
    "    def __init__(self, queens: list[cp_model.IntVar]):\n",
    "        cp_model.CpSolverSolutionCallback.__init__(self)\n",
    "        self._queens = queens\n",
    "        self._solution_count = 0\n",
    "        self._start_time = time.time()\n",
    "\n",
    "    @property\n",
    "    def solution_count(self) -> int:\n",
    "        return self._solution_count\n",
    "\n",
    "    def on_solution_callback(self) -> None:\n",
    "        current_time = time.time()\n",
    "        print(\n",
    "            f\"Solution{self._solution_count}, time =\"\n",
    "            f\" {current_time - self._start_time} s\"\n",
    "        )\n",
    "        self._solution_count += 1\n",
    "\n",
    "        all_queens = range(len(self._queens))\n",
    "        for i in all_queens:\n",
    "            for j in all_queens:\n",
    "                if self.value(self._queens[j]) == i:\n",
    "                    # There is a queen in column j, row i.\n",
    "                    print(\"Q\", end=\" \")\n",
    "                else:\n",
    "                    print(\"_\", end=\" \")\n",
    "            print()\n",
    "        print()\n",
    "\n",
    "\n",
    "def main(_):\n",
    "    board_size = _SIZE.value\n",
    "\n",
    "    ### Creates the solver.\n",
    "    model = cp_model.CpModel()\n",
    "\n",
    "    ### Creates the variables.\n",
    "    # The array index is the column, and the value is the row.\n",
    "    queens = [\n",
    "        model.new_int_var(0, board_size - 1, \"x%i\" % i) for i in range(board_size)\n",
    "    ]\n",
    "\n",
    "    ### Creates the constraints.\n",
    "\n",
    "    # All columns must be different because the indices of queens are all\n",
    "    # different, so we just add the all different constraint on the rows.\n",
    "    model.add_all_different(queens)\n",
    "\n",
    "    # No two queens can be on the same diagonal.\n",
    "    diag1 = []\n",
    "    diag2 = []\n",
    "    for i in range(board_size):\n",
    "        q1 = model.new_int_var(0, 2 * board_size, \"diag1_%i\" % i)\n",
    "        q2 = model.new_int_var(-board_size, board_size, \"diag2_%i\" % i)\n",
    "        diag1.append(q1)\n",
    "        diag2.append(q2)\n",
    "        model.add(q1 == queens[i] + i)\n",
    "        model.add(q2 == queens[i] - i)\n",
    "    model.add_all_different(diag1)\n",
    "    model.add_all_different(diag2)\n",
    "\n",
    "    ### Solve model.\n",
    "    solver = cp_model.CpSolver()\n",
    "    solution_printer = NQueenSolutionPrinter(queens)\n",
    "    # Enumerate all solutions.\n",
    "    solver.parameters.enumerate_all_solutions = True\n",
    "    # solve.\n",
    "    solver.solve(model, solution_printer)\n",
    "\n",
    "    print()\n",
    "    print(\"Statistics\")\n",
    "    print(\"  - conflicts       : %i\" % solver.num_conflicts)\n",
    "    print(\"  - branches        : %i\" % solver.num_branches)\n",
    "    print(\"  - wall time       : %f s\" % solver.wall_time)\n",
    "    print(\"  - solutions found : %i\" % solution_printer.solution_count)\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
